import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

abstract class BackgroundTask<V> implements Runnable,Future<V> {
    Callable<V> eval = new Callable<V>() {
        public V call() throws InterruptedException {
            Thread.sleep(1000);
            return null;
        }
    };
    private final FutureTask<V> computation = new Computation(eval);
    private class Computation extends FutureTask<V> {

        public Computation(Callable<V> callable) {
            super(new Callable<V>() {
                public V call() throws Exception {
                    return BackgroundTask.this.compute();
                }
            });
        }
    }
    protected final void done() {
        GuiExecutor.instance().execute(new Runnable() {
            public void run() {
                V value = null;
                Throwable thrown = null;
                boolean cancelled = false;
                try {
                    value = get();
                } catch(ExecutionException e) {
                    thrown = e.getCause();
                } catch (CancellationException e) {
                    cancelled = true;
                } catch(InterruptedException consumed) {

                } finally {
                    onCompletion(value,thrown,cancelled);
                }
            };
        }); 
    }
    protected void setProgress(final int current,final int max) {
        GuiExecutor.instance().execute(new Runnable() {
            public void run() {
                onProgress(current,max);
            }
        });
    }
    //在后台线程中被取消
    protected abstract V compute() throws Exception;
    //在事件线程中被取消
    protected void onCompletion(V result,Throwable exception,boolean cancelled) {}
    protected void onProgress(int current,int max) {}
}